package com.wjw.rabbit.work.fair;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 公平分发：生产者
 */
public class Producer {

    public static void main(String[] args) {
        //1.创建连接工程
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");//RabbitMQ服务的IP
        factory.setPort(5672);//端口
        factory.setUsername("admin");//RabbitMQ的用户
        factory.setPassword("admin");//RabbitMQ的密码
        factory.setVirtualHost("/");//虚拟访问节点

        Connection connection = null;
        Channel channel = null;

        try {
            //2.创建连接Connection
            connection = factory.newConnection("生产者");
            //3.创建连接获取通道Channel
            channel = connection.createChannel();

            for (int i = 1; i <= 20; i++) {
                String msg = "公平分发消息:"+i;
                /**
                 * 4.发送消息
                 * 参数一：交换机名称,这里为""代表默认交换机,AMQP default(direct类型的)
                 * 参数二：路由key/队列名
                 * 参数三：其他参数
                 * 参数四：发送的消息
                 */
                channel.basicPublish("","queue6",null,msg.getBytes());
                Thread.sleep(1000);
            }
            System.out.println("消息发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("消息发送异常！");
        } finally {
            //7.关闭通道
            if(channel != null && channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //8.关闭连接
            if(connection != null && connection.isOpen()){
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
